//
//  WBHomeViewController.swift
//  SainMicroblog
//
//  Created by chenxinju on 16/5/3.
//  Copyright © 2016年 chenxinju-a2. All rights reserved.
//

import UIKit
import SVProgressHUD


/// 重用标识
let WBHomeViewControllerReusableIdentifier = "WBHomeViewControllerReusableIdentifier"

class WBHomeViewController: WBBaseTableViewController {
    
    
    
    ///  view不能直接拥有model
    /// view只能拥有viewModel
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        //=====================注册闭包回调
        func closure() {
            print("闭包调用注册在此方法跳转注册页面")
        }
        func loginClosure() {
            print("登录闭包回调,跳转登录界面")
        }
       //===================================
       //====================================
        
        if isLogin { //判断是否登录
            //如果登录了,我们要通过token去请求数据
            //单例获取Token
            WBOauthViewModel.shareInstance.access_token
            
            //获取数据的方法
            loadData()
            
            //======================注册cell
            tableView.registerClass(WBHomeTableViewCell.self, forCellReuseIdentifier: WBHomeViewControllerReusableIdentifier)
            tableView.rowHeight = UITableViewAutomaticDimension
            //设置预估行高
            tableView.estimatedRowHeight = 150
            //添加上拉显示条
            tableView.tableFooterView = pullView
             //添加下拉刷新
            tableView.addSubview(refrshView)
            
            //注册监听
            self.refrshView.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
            
            /*
            第一个参数： 观察者。观察者需要实现 observeValueForKeyPath 这个方法
            第二个参数： 要观察的属性值
            第三个参数： 值的改变
            第4个参数： nil
            */
            //  tableView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        
            
        }else { //显示主页访客视图
            visitloginVIew?.setupInfo("关注一些人,回这里看看有什么惊喜", image: nil)
        }
        
        ///第三步:注册闭包赋值
        visitloginVIew?.resisterClose = closure
        ///登录闭包属性赋值
        visitloginVIew?.resisLogin = loginClosure
        
    }
    
    //加载数据调用
    @objc  private  func loadData(){
        var since_id = 0
        var max_id = 0
        //加载忙的提示
        SVProgressHUD.show()
        //如果在转动 需要上拉跟多
        
    since_id = WBStatusListModel.shareInstance.statusList.first?.status?.id ?? 0
    
        //需要上拉更多的时候修改max_id
        if pullView.isAnimating(){
          max_id = WBStatusListModel.shareInstance.statusList.last?.status?.id ?? 0
            
            //再次确保id 为0
             since_id = 0
        }
        
        WBStatusListModel.shareInstance.loadData(since_id, max_id: max_id, sccess: { (count) -> () in
            
            //成功的回调 完成之后刷新数据
            self.tableView.reloadData()
            
            //更新一下提示
            if !self.pullView.isAnimating() {
              self.show(count)
            
            }
            
           //加载完成之后停止转动
           self.pullView.stopAnimating()
             //停止拖拽调用
           self.refrshView.endRefreshing()
            
            SVProgressHUD.dismiss()
            
            }) { (error) -> () in
                printLog(error)
                //失败的
                SVProgressHUD.dismiss()
        }
        
    }
   
    //加载提示更新弹框
  private  func show(count: Int) {
        let labeleHeigth:CGFloat = 35
        let label = UILabel(frame: CGRectMake(0, 64 - labeleHeigth, WBUIScreenW, labeleHeigth))
        label.backgroundColor = UIColor.orangeColor()
        label.textAlignment = .Center
        
        label.font = UIFont.systemFontOfSize(16)
        label.textColor = UIColor.blackColor()
        
        if count > 0 {
        
           label.text = "更新了\(count)条微博"
        }else if count == 0{
        
           label.text = "暂时无更新"
        }else {
       
           return
       }
        
        //添加到当前的view中
        view.addSubview(label)
      
        //插入到当前的导航栏里面
        navigationController?.view.insertSubview(label, belowSubview: (navigationController?.navigationBar)!)
        
      UIView.animateWithDuration(2, animations: { () -> Void in
              //动画出来
             label.transform = CGAffineTransformMakeTranslation(0, labeleHeigth)
        
        }) { (_ ) -> Void in
            
          //完成之后弹回去
            UIView.animateWithDuration(2, animations: { () -> Void in
                  label.transform = CGAffineTransformIdentity
                }, completion: { (_) -> Void in
                 //动画全部完成
                label.removeFromSuperview()
                    
            })
        }
    }

    //MARK:- 懒加载控件
  private lazy var pullView:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    
private lazy var refrshView:WBRefreshController = WBRefreshController()
    
}

//MARK:-- UITableViewDatasoure
extension WBHomeViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return WBStatusListModel.shareInstance.statusList.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        
        
        let cell = tableView.dequeueReusableCellWithIdentifier(WBHomeViewControllerReusableIdentifier, forIndexPath: indexPath) as! WBHomeTableViewCell
        
        cell.statusViewModel = WBStatusListModel.shareInstance.statusList[indexPath.row]
        
        //当数据显示到倒数 2条cell时 让旋转显示
        if indexPath.row == WBStatusListModel.shareInstance.statusList.count - 2 {
            
            pullView.startAnimating()

            //加载数据
            loadData()
            
        }
        
        return cell
    }
    
}
